<template>
    <h1 class="title_text">消费数据总览</h1>
    <el-calendar ref="calendar" v-model="value">
        <template #date-cell="{ data }">
            <p :class="data.isSelected ? 'is-selected' : ''">
                {{ data.day.split("-").slice(1).join("-") }}
            </p>
            <span v-if="expenses[data.day]" class="expense">¥{{ expenses[data.day] }}</span>
        </template>
        <template #header="{ date }">
            <span>{{ date }}</span>
            <el-button-group>
                <el-button size="small" @click="selectDate('prev-year')">上一年</el-button>
                <el-button size="small" @click="selectDate('prev-month')">上一月</el-button>
                <el-button size="small" @click="selectDate('today')">今日</el-button>
                <el-button size="small" @click="selectDate('next-month')">下一月</el-button>
                <el-button size="small" @click="selectDate('next-year')">下一年</el-button>
            </el-button-group>
        </template>
    </el-calendar>
</template>

<script lang="ts" setup>
import { reactive, ref, computed,onMounted, watch } from "vue";
import type { CalendarDateType, CalendarInstance } from "element-plus";
import { getCalendarShowDataAPI } from "src/httpApi/dataAnalysisHttp";

const value: any = ref(new Date())
const calendar = ref<CalendarInstance>();
const expenses: any = reactive({});

const selectDate = (val: CalendarDateType) => {
    if (!calendar.value) return;
    calendar.value.selectDate(val);
};

// 模拟获取花销数据的函数
const fetchExpenses =async (month: string) => {
    const res = await getCalendarShowDataAPI({"month":month});
    return res.result;
}

const getMonthAndYear = (date: Date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    return `${year}-${month}`;
};

const currentMonth = computed(() => {
    return getMonthAndYear(value.value);
});

// 监听日期变化，获取对应月份的花销数据
watch(currentMonth,async (newMonth) => {
    const monthExpenses =await fetchExpenses(newMonth);
    Object.assign(expenses, monthExpenses);
});

// 页面加载时获取当前月份的花销数据
onMounted(async () => {
    const initialMonth = getMonthAndYear(value.value);
    const initialExpenses = await fetchExpenses(initialMonth);
    Object.assign(expenses, initialExpenses);
});

</script>

<style scoped>
.title_text {
    font-size: 28px;
    font-weight: 600;
    color: #333;
    margin-bottom: 20px;
}

.is-selected {
    color: #1989fa;
}

.expense {
    display: block;
    text-align: right;
    color: #ff0000;
    font-size: 20px;
    margin-right: 16px;
}
</style>
